package com.supereasy.kotlincor

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.supereasy.kotlincor.http.MyUrl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttp
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

class LifeCycleCoroutineActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_life_cycle_coroutine)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        doSomething()
    }

    fun doSomething() {
        // 一、
//        lifecycleScope.launch {
//            val result = withContext(Dispatchers.IO) {
//                getResult()
//            }
//            findViewById<TextView>(R.id.text).setText(result)
//        }

        // 二、
//        lifecycleScope.launch(Dispatchers.IO) {
//            val result = getResult()
//            withContext(Dispatchers.Main) {
//                findViewById<TextView>(R.id.text).setText(result)
//            }
//        }

//        // 三、
//        lifecycleScope.launch {
//            val result = getCorResult()
//            findViewById<TextView>(R.id.text).setText(result.getOrNull())
//        }

    }

    private suspend fun getResult(): String? {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(MyUrl.url)
            .build()
        val response = client.newCall(request).execute()
        return response.body?.string()
    }

    private suspend fun getCorResult(): Result<String> {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(MyUrl.url)
            .build()
        return suspendCoroutine { con ->
            client.newCall(request).enqueue(object : Callback{
                override fun onFailure(call: Call, e: IOException) {
                    con.resumeWithException(RuntimeException())
                }

                override fun onResponse(call: Call, response: Response) {
                    con.resume(Result.success(response.body?.string()?: ""))
                }
            })
        }
    }

}